package org.jetnuke.modules.blog;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.ActionServletRequest;
import net.jforum.JForumExecutionContext;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import net.jforum.util.legacy.commons.fileupload.FileItem;
import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.BlogSettings;
import org.jetnuke.servlets.utilities.StringUtils;
import org.jetnuke.util.JetUtil;

public class UploadResource implements IAction {
	
	
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		
		
		if(ui==null || ui.getID()<2)
			return null;
		String initPath=SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/blog/"+ui.getID()+"/";
		//String path = sc.getRealPath(initPath);
		File pathDir=new File(initPath);
		if(!pathDir.exists()){
			pathDir.mkdirs();
		}
		
		
		
		ActionServletRequest asr=JForumExecutionContext.getRequest();
		FileItem file=(FileItem)asr.getObjectParameter("file");
		long fileSize=file.getSize();
		long resourcesSize=getResourcesSize(0,pathDir);
		BlogSettings bs=DataAccessDriver.getInst().newBlogSettingsDAO().get();
		boolean isSuperUser = ai!=null && ai.IsSuperUser();
		if(((resourcesSize+fileSize)>1024*bs.getLIMIT())&& !isSuperUser){
			return new ActionForward(info,"no_space.vm");
		}
		
		
		String realName = file.getName();
		
		String simplifiedName=StringUtils.getSimpleFileName(realName);
		File f = new File(pathDir,simplifiedName);
		OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(f));
		byte[] b = new byte[2048];
		BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());
		while ((inputStream.read(b)) != -1) {
			outputStream.write(b);
		}
		
		outputStream.flush();
		outputStream.close();
		inputStream.close();
		JetUtil.redirect(vc,response,request.getContextPath()+"/do/blog/resources");
		return null;
	}

	public static  long getResourcesSize(long initSize,File pathDir) {
		File f[]=pathDir.listFiles();
		long ret=initSize;
		for(int i=0;i<f.length;i++){
			if(f[i].isFile()){
				ret=ret+f[i].length();
			}else{
				ret=getResourcesSize(ret,f[i]);
			}
		}
		return ret;
	}

}
